package com.resou.reader.reader.view;

import android.content.Context;
import android.graphics.Canvas;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.resou.reader.ReSouApplication;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.reader.animation.BaseAnimation;
import com.resou.reader.reader.animation.RealAnimation;
import com.resou.reader.reader.manager.PageFactory;
import com.resou.reader.reader.utils.ScreenUtils;
import com.resou.reader.utils.DeviceUtils;
import com.resou.reader.utils.NetworkUtils;
import com.resou.reader.utils.PreferenceUtil;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.log.DLog;

import static com.resou.reader.reader.utils.ViewUtils.measureSize;

/**
 * Created by ${Garrett} on 2018/9/8.
 * Contact me krouky@outlook.com
 */
public class PageView extends View {

    public static final String TAG = "调试";
    private int defaultWidth = 600;//默认宽度
    private int defaultHeight = 1000;//默认高度
    private boolean canPage = true;//是否可以翻页 ，当弹出setting的时候不响应翻页

    //*********************外部必须设置的成员********************
    private BaseAnimation animation;
    private PageFactory pageFactory;

    public PageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setWillNotDraw(false);
        defaultHeight = ScreenUtils.getScreenHeight();
        defaultWidth = ScreenUtils.getScreenWidth();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        super.measure(widthMeasureSpec, heightMeasureSpec);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = measureSize(defaultHeight, heightMeasureSpec);
        int width = measureSize(defaultWidth, widthMeasureSpec);
        setMeasuredDimension(width, height);
    }

//    @Override
//    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
//        super.layout(left, top, right, bottom);
//        pageFactory.setCanvasArea(getMeasuredWidth(), getMeasuredHeight());
//        animation.onMeasure(getMeasuredWidth(), getMeasuredHeight());
//    }


    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        pageFactory.setCanvasArea(getMeasuredWidth(), getMeasuredHeight());
        animation.onMeasure(getMeasuredWidth(), getMeasuredHeight());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //由于不同的动画主要逻辑在onDraw里面，所以我们把onDraw的具体操作放在各自的动画类中实现
        animation.onDraw(canvas);
    }

    boolean isOnButton = false;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (pageFactory.isClickedPay(event) || pageFactory.isClickedBatchPay(event) || pageFactory.selectAutoBuy(event) ||
                    pageFactory.isClickedEnergyDeduction(event) || pageFactory.isClickedVipPay(event) ||
                    pageFactory.isClickedResouForMePay(event) || pageFactory.refreshUnshelfData(event) ||
                    pageFactory.refreshNoNetworkfView(event)) {
                isOnButton = true;
                return true;
            } else {
                if (!isCanPage()) {
                    return false;
                }
                return animation.onTouchEvent(event);//把事件给animation
            }
        } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
            if (isOnButton) {
                return false;
            } else {
                return animation.onTouchEvent(event);//把事件给animation
            }
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            if (isOnButton) {
                isOnButton = false;
                /**
                 * 无网络点击事件
                 */
                if (pageFactory.refreshNoNetworkfView(event)) {
                    if (NetworkUtils.isNetworkConnected(getContext())) {
                        pageFactory.getPresenter().showLoading("");
                        if (pageFactory.getPresenter().getChapterList().size() > 0) {
                            pageFactory.toSpecifyChapter(pageFactory.getChapterIndex(), false);
                        } else {
                            pageFactory.getPresenter().getCatalogue(pageFactory.getPresenter().getBookId(), UserInstance.getToken(), DeviceUtils.getIMEI(getContext()), pageFactory.getChapterIndex());
                        }
                    } else {
                        ToastUtil.makeShortToast("网络异常");
                        pageFactory.getPresenter().refreshPageView();
                    }
                    return false;
                }
                if (pageFactory.refreshUnshelfData(event)) {
                    pageFactory.getPresenter().showLoading("");
//                    ToastUtil.makeShortToast("重新获取");
                    pageFactory.toSpecifyChapter(pageFactory.getChapterIndex(), false);
                    return false;
                }
                if (pageFactory.isClickedPay(event)) {
                    if (!NetworkUtils.isNetworkConnected(getContext())) {
                        ToastUtil.makeShortToast("网络异常");
                        return false;
                    }
                    //判断是否已经开启三天限时充值
                    PreferenceUtil util = PreferenceUtil.getInstance(ReSouApplication.getRSApplication());
                    if (util.isShowRechargeDialogShowInReader()) {
                        pageFactory.getPresenter().showLimitedRechargeDialog();
                    } else {
                        /**
                         * 判断是否选中自动购买且点击购买按钮，且服务器那边没有设置为自动购买时，
                         *先调用自动购买
                         */
                        if (pageFactory.getIsAutoBuy() && !pageFactory.getPresenter().isAutoBuy()) {
                            pageFactory.selectAutoBuy(true);
                            pageFactory.pay(false);
                        } else {
                            pageFactory.pay(false);
                        }
                        return false;
                    }
                }

                /**
                 * 批量购买章节
                 */
                if (pageFactory.isClickedBatchPay(event)) {
                    if (NetworkUtils.isNetworkConnected(getContext())) {
                        pageFactory.pay(true);
                    } else {
                        ToastUtil.makeShortToast("网络异常");
                    }
                    return false;
                }
                /**
                 * 点击能量值活动
                 */
                if (pageFactory.isClickedEnergyDeduction(event)) {
                    pageFactory.getPresenter().startToFriendBoostActivity();
                    return false;
                }
                if (pageFactory.isClickedResouForMePay(event)) {
                    if (NetworkUtils.isNetworkConnected(getContext())) {
                        pageFactory.getPresenter().showSubSidyDialog();
                    } else {
                        ToastUtil.makeShortToast("网络异常");
                    }
                    return false;
                }
                /**
                 * 开通VIp
                 */
                if (pageFactory.isClickedVipPay(event)) {
                    if (!NetworkUtils.isNetworkConnected(getContext())) {
                        ToastUtil.makeShortToast("网络异常");
                        return false;
                    }
                    pageFactory.getPresenter().startVipSubMonthlytActivity();
                    return false;
                }
                /**
                 * 点击自动购买
                 */
                if (pageFactory.selectAutoBuy(event)) {
                    if (!NetworkUtils.isNetworkConnected(getContext())) {
                        ToastUtil.makeShortToast("网络异常");
                        return false;
                    }
                    pageFactory.setAutoBuy();
                    refresh();
                    return false;
                }

            } else {
                return animation.onTouchEvent(event);//把事件给animation
            }
        }
//        if (pageFactory.isShowView()) {
//            float advertHeight = pageFactory.getAdvertTouchHeight();
//            if (event.getY() >= pageFactory.getAdViewY() && event.getY() <= pageFactory.getAdViewY() + advertHeight) {
//                boolean isTouch = true;
//                if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
////                    pagefactory.onDraw(mCurrentPageCanvas);
////                    pagefactory.onDraw(mNextPageCanvas);
////                    postInvalidate();
//                    if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
//                        isTouch = false;
//                    } else {
//                        pageFactory.onAdViewTouchEvent(event);
//                    }
//                }
//                if (isTouch) {
//                    return true;
//                }
//            }
//        }
        return false;
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        animation.computeScroll();
    }

    public void init(BaseAnimation animation, PageFactory pageFactory) {
        if (animation == null)
            throw new NullPointerException("init BaseAnimation == null");
        this.pageFactory = pageFactory;
        this.animation = animation;
        animation.bindView(this);
        animation.setPageFactory(pageFactory);
    }


    public void setAnimation(BaseAnimation animation) {
        this.animation = animation;
        animation.bindView(this);
        animation.setPageFactory(pageFactory);
        animation.onMeasure(getMeasuredWidth(), getMeasuredHeight());

        if (this.animation instanceof RealAnimation) {
            ((RealAnimation) animation).onBackgroundChange(pageFactory.getBgColor());
        }
    }

    public void onBackgroundChange(int color) {
        if (this.animation instanceof RealAnimation) {
            ((RealAnimation) animation).onBackgroundChange(color);
        }
        pageFactory.setBgColor(color);
    }

    public void refreshCurrPage() {
        animation.refreshCurrPage();
        postInvalidate();
    }

    public void refreshNextPage() {
        animation.refreshNextPage();
        postInvalidate();
    }

    public void refresh() {
        Log.i(TAG, "refresh: " + pageFactory.isRecycled());
        animation.refreshCurrPage();
        animation.refreshNextPage();
        postInvalidate();
        Log.i(TAG, "refresh: " + pageFactory.isRecycled());

    }

    public boolean isCanPage() {
        return canPage;
    }

    public void setCanPage(boolean canPage) {
        this.canPage = canPage;
    }

    /**
     * 音量键翻页（下一页）
     */
    public void nextPage() {
        animation.nextPage();
    }

    /**
     * 音量键翻页（上一页）
     */
    public void prePage() {
        animation.prePage();
    }
}
